<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 16:36:53
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-28 10:48:28
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\EquipType\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, watch, reactive, h } from 'vue'
import { ElTree, ElInput, ElTag } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useDictStore } from '@/store/modules/dictData'
import { useDeptStore } from '@/store/modules/dept'
import { BaseButton } from '@/components/Button'
import SecurCheckLedgerApi from '@/api/securcheck/LedgerMessage'
import DeptApi from '@/api/dept'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { CompanyLedger } from '@/api/securcheck/type'
import SecurCheckComLedgerApi from '@/api/securcheck/CompanyLedger'
import { flatData } from '@/hooks/PublicFun'
import Write from './components/write.vue'
const { t } = useI18n()
const ids = ref<string[]>([])
const DeptStore = useDeptStore()
const treeEl = ref<typeof ElTree>() //树结构
const currentNodeKey = ref<number>() //树结构ID
const departmentList = ref<any>([]) //树结构数据
const Title = ref<string | undefined>('表单台账') //表格名称
const DictStore = useDictStore()
//获取字典
DictStore.setDict('secur_user_state') //用户状态
DictStore.setDict('secur_user_type') //用户类型
DictStore.setDict('secur_y_n') //气代煤用户
DictStore.setDict('secur_is_oov') //气源类型
DictStore.setDict('secur_gas_type') //气源类型
if (DeptStore.DeptListTypeDetail.length == 0) {
  DeptStore.setFacilityTypeDetail()
}
//表格内容接口
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const i = await SecurCheckComLedgerApi.GetCompanyLedger({
      areaId: unref(currentNodeKey),
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await SecurCheckComLedgerApi.DeletCompanyLedger(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const FormDisabled = ref(true)
//表格结构
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    type: 'selection',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    fixed: 'left'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    fixed: 'left',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'field1',
    label: '管理属性',
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Divider',
      componentProps: {
        contentPosition: 'center'
      }
    }
  },
  {
    field: 'companyState',
    label: t('单位状态'),
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.secur_user_state?.map((item) => {
        if (item.dictValue == cellValue) {
          return h(ElTag, { type: item.listClass }, () => t(item.dictLabel))
        }
      })
    },
    search: {
      component: 'Select',
      componentProps: {
        placeholder: '单位状态',
        options: DictStore.$state.secur_user_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_user_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'companyName',
    label: t('单位名称'),
    width: 100,
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '单位名称'
      }
    }
  },
  {
    field: 'companyNo',
    label: t('单位编号'),
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '单位编号'
      }
    },
    width: 100
  },
  {
    field: 'companyPhone',
    label: t('单位电话'),
    width: 100,
    search: {
      hidden: true
    }
  },
  {
    field: 'companyAddre',
    label: t('单位地址'),
    width: 200,
    search: {
      hidden: true
    }
  },
  {
    field: 'oaDate',
    label: t('开户日期'),
    width: 150,
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'coEndDate',
    label: t('合同截止日期'),
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'deptId',
    label: t('所属公司'),
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        checkStrictly: true,
        checkOnClickNode: true,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      },
      optionApi: async () => {
        const res = await DeptApi.GetDeptListTree()
        return res.data
      }
    }
  },
  {
    field: 'areaId',
    label: t('用户片区'),
    width: 120,
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return flatData(departmentList.value).map((item) => {
        if (item.id == cellValue) {
          return t(item.label)
        }
      })
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        renderAfterExpand: false,
        checkOnClickNode: true,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      },
      optionApi: () => {
        const res = departmentList.value
        return res
      }
    }
  },
  {
    field: 'isPlanSub',
    label: t('是否计划填报'),
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.secur_y_n?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'meterCount',
    label: t('表具数量'),
    width: 100,
    search: {
      hidden: true
    },
    form: {
      componentProps: {
        disabled: true
      }
    }
  },
  {
    field: 'devMainGas',
    label: t('主要用气设备'),
    width: 150,
    search: {
      hidden: true
    }
  },

  {
    field: 'userType',
    label: t('用户类型'),
    width: 100,
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.secur_user_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_user_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isPos',
    label: t('是否定位'),
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isManage',
    label: t('是否纳入管理'),
    width: 200,
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isCopyInfo',
    label: t('是否抄其他信息'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isAlarm',
    label: t('是否安装报警器'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isMetalhose',
    label: t('是否安装金属软管'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isScv',
    label: t('是否安装自闭阀'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isRemTrans',
    label: t('是否关联远传'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isEnergys',
    label: t('是否双能源'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'isStopGas',
    label: t('是否可以中断用气'),
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_y_n?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'gasType',
    label: t('气源类型'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_gas_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'energysType',
    label: '双能源类型',
    table: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'contacts',
    label: '用户分类',
    table: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'createBy',
    label: t('创建者'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      componentProps: {
        disabled: true
      }
    }
  },
  {
    field: 'createTime',
    label: t('创建时间'),
    width: 200,
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      componentProps: {
        disabled: true
      }
    }
  },

  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'Edit')}>
                {t('修改')}
              </span>
              <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                {t('查看')}
              </span>

              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const fetchDepartment = async () => {
  const res = await SecurCheckLedgerApi.GetUserAreaTree('')
  departmentList.value = res
}
fetchDepartment() //获取树结构
const currentDepartment = ref('') //树结构搜索框内容
watch(
  () => currentDepartment.value, //监控树结构搜索框内容变化
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  //树结构点击
  currentNodeKey.value = data.id
  Title.value = data.label
  currentPage.value = 1 //页面为第一页
  getList() //表格更新
}
const filterNode = (value: string, data: any) => {
  //树结构变化
  if (!value) return true
  return data.label.includes(value)
}
const currentRow = ref<CompanyLedger>()
const saveLoading = ref(false)
const delLoading = ref(false)
//表格删除操作
const delData = async (row: CompanyLedger | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const ComLedgerRef = ref()
const actionType = ref('')

const save = async () => {
  const write = unref(ComLedgerRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await SecurCheckComLedgerApi.AddCompanyLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else if (actionType.value == 'Edit') {
      //修改字
      res.value = await SecurCheckComLedgerApi.EditCompanyLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
  if (actionType.value == 'Detail') {
    dialogVisible.value = false
  }
}
//表格中操作
const action = async (row: CompanyLedger, type: string) => {
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  if (type == 'add') {
    dialogTitle.value = '新增'
    FormDisabled.value = false
    currentRow.value = {}
  } else if (type == 'Edit') {
    const res = await SecurCheckComLedgerApi.GetCompanyLedgerById(row.uuid)
    dialogTitle.value = '修改'
    FormDisabled.value = false
    currentRow.value = res
  } else {
    const res = await SecurCheckComLedgerApi.GetCompanyLedgerById(row.uuid)
    dialogTitle.value = '查看'
    FormDisabled.value = true
    currentRow.value = res
  }
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]" title="用户片区">
      <ElInput
        v-model="currentDepartment"
        class="flex-[2] mb-[10px]"
        :placeholder="t('组织名称')"
        clearable
      />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'departmentName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.label" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.label }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px" :title="Title">
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="13" />新增
      </BaseButton>
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        row-key="uuid"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        ref="ComLedgerRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :FormDisabled="FormDisabled"
      />
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped>
/* .el-tree {
  height: 410px;
  overflow: hidden;
  overflow-y: scroll;
} */
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
.el-card__body {
  padding: 10px;
  /* height: 90%; */
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
